//
//  M1MessageViewController.m
//  NewMarryU
//
//  Created by apple on 2018/7/21.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1MessageViewController.h"
#import <MapKit/MapKit.h>
#import <IQKeyboardManager.h>
#import "M1MessageHeader.h"
#import "M1EditInformationTextFieldVC.h"
#import "M1RealNameViewController.h"
#import "M1HomeModel.h"
@interface M1MessageViewController ()<UIAlertViewDelegate,EMClientDelegate>
{
    UIMenuItem *m1_copyItem;
    UIMenuItem *m1__deleteItem;
    UIMenuItem *m1_transpondItem;
    UIMenuItem *m1_recallItem;
}
@property (nonatomic) BOOL   isPlayingAudio;
@property(nonatomic,assign)BOOL isSend;
@property (nonatomic) NSMutableDictionary *emotionDic;
@property (nonatomic, copy) EaseSelectAtTargetCallback selectedCallback;
@end

@implementation M1MessageViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:m1_boldFont(16),NSForegroundColorAttributeName:[UIColor m1_colorHex:0x333333]}];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar=NO;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[EMClient sharedClient] removeDelegate:self];
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (_isRemove) {
        NSMutableArray *m1_vcs = [self.navigationController.viewControllers mutableCopy];
        [m1_vcs removeObjectAtIndex:m1_vcs.count-2];
        self.navigationController.viewControllers = m1_vcs;
    }
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;
    
    UIView *m1_nav = [[UIView alloc]init];
    m1_nav.backgroundColor = m1_bg_color;
    [self.view addSubview:m1_nav];
    [m1_nav mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.mas_offset(m1_NAV_HEIGHT);
    }];
    
    UIButton * m1_backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [m1_backBtn setImage:[[UIImage imageNamed:@"black_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:0];
    [m1_backBtn addTarget:self action:@selector(m1_back) forControlEvents:UIControlEventTouchUpInside];
    [m1_backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 10)];
    [m1_nav addSubview:m1_backBtn];
    [m1_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.bottom.offset(0);
        make.height.mas_offset(44);
        make.width.mas_offset(60);
    }];
    
    UILabel *m1_titleLB = [[UILabel alloc]init];
    m1_titleLB.textColor = [UIColor m1_colorHex:0x333333];
    m1_titleLB.font = m1_boldFont(17);
    m1_titleLB.text = self.navigationItem.title;
    m1_titleLB.textAlignment = NSTextAlignmentCenter;
    [m1_nav addSubview:m1_titleLB];
    
    [m1_titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.centerX.equalTo(m1_nav);
        make.height.mas_offset(44);
        make.width.mas_offset(200);
    }];
    
    self.tableView.contentInset = UIEdgeInsetsMake(m1_NAV_HEIGHT-STATUS_HEIGHT, 0, 0, 0);
    if (!_m1_isSysTem) {
        M1MessageHeader *m1_header = [[M1MessageHeader alloc]init];
        [self.view addSubview:m1_header];
        WEAKSELF;
        m1_header.click = ^(M1HeaderClickType clickType) {
            if (clickType == M1HeaderClickType_Check) {
                [weakSelf m1_goDetail];
            }
            
            if (clickType == M1HeaderClickType_ChangeWX) {
                //微信交换权限
                [weakSelf m1_exchangeWxPermission];
            }
            
            if (clickType == M1HeaderClickType_Black) {
                [[M1User user] m1_joinblocklist:weakSelf.m1_uid];
            }
        };
        [m1_header mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.top.offset(m1_NAV_HEIGHT);
            make.height.mas_offset(64);
        }];
        
        
        self.tableView.contentInset = UIEdgeInsetsMake(m1_NAV_HEIGHT+64-STATUS_HEIGHT, 0, 0, 0);
    }
}

-(void)m1_goDetail{
    NSArray *array = self.navigationController.viewControllers;
    if ([array[array.count - 2] isKindOfClass:[M1HomeDetailsVC class]]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    NSDictionary *dic = [[EaseDataBase sharedDataBase] queryWeixinWithSessionId:self.conversation.conversationId];
    M1HomeModel *m1_homeModel = [M1HomeModel new];
    M1HomeBasic *m1_basic = [M1HomeBasic new];
    m1_basic.uid = [dic m1_stringKey:@"uid"];
    m1_homeModel.basic = m1_basic;
    M1HomeDetailsVC *m1_detailVC = [[M1HomeDetailsVC alloc]init];
    m1_detailVC.m1_hiddenNav = YES;
    m1_detailVC.m1_model = m1_homeModel;
    [self.navigationController pushViewController:m1_detailVC animated:YES];
}
    
-(void)checkFirstSend{
    if(_isSend||[self.conversation.conversationId isEqualToString:[@"100000" m1_MD5]]||[self.conversation.conversationId isEqualToString:[@"100001" m1_MD5]]||[self.conversation.conversationId isEqualToString:[@"100002" m1_MD5]]||[self.conversation.conversationId isEqualToString:[@"100003" m1_MD5]]){
        return;
    }
    
    WEAKSELF;
    [M1HttpNet requestWithMethod:m1_chat_url params:@{@"to_uid":_m1_uid} success:^(id resDic, NSInteger code, NSString *message) {
        weakSelf.isSend = YES;
    } fail:^(id resDic, NSInteger code, NSString *message) {
        
    } showAni:NO];
}
    
#pragma mark -微信交换权限
-(void)m1_exchangeWxPermission{
    WEAKSELF;
    [M1HttpNet requestWithMethod:m1_wechat_power_url params:@{@"wechat_type":@"0",@"to_uid":_m1_uid} success:^(id resDic, NSInteger code, NSString *message) {
        NSDictionary *dic = resDic[0];
        if ([dic[@"if_exchange_wechat"] boolValue]) {
            //已经交换过微信
            NSString *m1_to_wx = [dic m1_stringKey:@"to_wechat"];
            NSDictionary *ext = @{@"hx_attr_show_wx_account":@(YES),
                                  @"hx_attr_show_other_wx_account":m1_to_wx,
                                  @"hx_attr_show_my_wx_account":[dic m1_stringKey:@"me_wechat"]
                                  };
            NSString *m1_name = weakSelf.navigationItem.title;
            if (m1_name.length >6) {
                m1_name = [NSString stringWithFormat:@"%@...",[m1_name substringWithRange:NSMakeRange(0, 6)]];
            }
            NSString *str = [NSString stringWithFormat:@"%@的微信号：%@",m1_name,m1_to_wx];
            EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:str];
            NSString *from = [[EMClient sharedClient] currentUsername];
            EMMessage *message = [[EMMessage alloc] initWithConversationID:weakSelf.conversation.conversationId from:from to:weakSelf.conversation.conversationId body:body ext:ext];
            message.chatType = EMChatTypeChat;
            [[EMClient sharedClient].chatManager importMessages:@[message] completion:^(EMError *aError) {
                id<IMessageModel> model = nil;
                model = [[EaseMessageModel alloc] initWithMessage:message];
                model.avatarImage = [UIImage imageNamed:@"EaseUIResource.bundle/user"];
                model.avatarURLPath = [model.message.ext m1_stringKey:@"headphoto"];
                model.nickname = [model.message.ext m1_stringKey:@"nick_name"];
                model.failImageName = @"imageDownloadFail";
                [weakSelf.dataArray addObject:model];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }];
        }else{
            NSDictionary *ext = @{@"hx_attr_exchange_wx":@(YES),
                                  @"hx_attr_exchange_wx_enable":@(YES),
                                  };
            [weakSelf sendTextMessage:@"我想和你交换微信，您是否同意？" withExt:ext];
        }
    } fail:^(id resDic, NSInteger code, NSString *message) {
        if (code == -10014) {
            //会员
            [M1Alert m1_alertWithTitle:nil message:@"只有成为加V会员才能和Ta人交换微信号" buttonTitles:@[@"取消",@"确定"] action:^(NSInteger index) {
                if (index == 1) {
                   //会员
                }
            }];
        }else if (code == -70000){
            //填写微信
            [M1Alert m1_alertWithTitle:nil message:message buttonTitles:@[@"取消",@"确定"] action:^(NSInteger index) {
                if (index == 1) {
                    M1EditInformationTextFieldVC *textfieldVC = [[M1EditInformationTextFieldVC alloc] init];
                    textfieldVC.titleStr = @"微信号";
                    [weakSelf.navigationController pushViewController:textfieldVC animated:YES];
                }
            }];
        }else if (code == -40000){
            [M1Alert m1_alertWithTitle:nil message:message buttonTitles:@[@"取消",@"确定"] action:^(NSInteger index) {
                if (index == 1) {
                    M1RealNameViewController *m1_idenVC = [[M1RealNameViewController alloc] init];
                    [weakSelf.navigationController pushViewController:m1_idenVC animated:YES];
                }
            }];
        }
        else{
            [M1Alert m1_alertWithTitle:nil message:message];
        }
    } showAni:YES];
}

-(void)m1_back{
    if (self.deleteConversationIfNull) {
        EMMessage *message = [self.conversation latestMessage];
        if (message == nil) {
            [[EMClient sharedClient].chatManager deleteConversation:self.conversation.conversationId isDeleteMessages:NO completion:nil];
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)tableViewDidTriggerHeaderRefresh {
    
    if ([[EaseChatHelper shareHelper] isFetchHistoryChange]) {
        NSString *startMessageId = nil;
        if ([self.messsagesSource count] > 0) {
            startMessageId = [(EMMessage *)self.messsagesSource.firstObject messageId];
        }
        [EMClient.sharedClient.chatManager asyncFetchHistoryMessagesFromServer:self.conversation.conversationId
                                                              conversationType:self.conversation.type
                                                                startMessageId:startMessageId
                                                                      pageSize:10
                                                                    completion:^(EMCursorResult *aResult, EMError *aError)
         {
             [super tableViewDidTriggerHeaderRefresh];
         }];
    } else {
        [super tableViewDidTriggerHeaderRefresh];
    }
}
#pragma mark - EaseMessageViewControllerDelegate
-(void)messageOption:(id<IMessageModel>)model index:(NSInteger)index{
    WEAKSELF;
    if ([[model.message.ext m1_stringKey:@"hx_attr_exchange_wx"] boolValue]) {
        if (index == 0) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:model.message.ext];
            [dic setValuesForKeysWithDictionary:@{@"hx_attr_exchange_wx":@(YES),
                                                  @"hx_attr_exchange_wx_enable":@(NO),
                                                  }];
            model.message.ext = dic;
            [[EMClient sharedClient].chatManager updateMessage:model.message completion:^(EMMessage *aMessage, EMError *aError) {
            }];
            NSDictionary *ext = @{@"hx_attr_refuse_exchange_wx_account":@(YES),
                                  @"hx_attr_refuse_exchange_wx_account_other":@"对方拒绝了您的微信交换请求",
                                  @"hx_attr_refuse_exchange_wx_account_my":@"您拒绝了对方的微信交换请求"
                                  };
            NSString *str = @"对方拒绝了您的微信交换申请";
            [self sendTextMessage:str withExt:ext];
        }
        if (index == 1) {
            [M1HttpNet requestWithMethod:m1_wechat_agree_url params:@{@"to_uid":_m1_uid} success:^(id resDic, NSInteger code, NSString *message) {
                NSDictionary *m1_dic = resDic[0];
                
                NSString *weixin = [m1_dic m1_stringKey:@"me_wechat"];
                NSString *to_weixin = [m1_dic m1_stringKey:@"to_wechat"];
                NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:model.message.ext];
                [dic setValuesForKeysWithDictionary:@{@"hx_attr_exchange_wx":@(YES),
                                                                          @"hx_attr_exchange_wx_enable":@(NO),
                                                                          }];
                model.message.ext = dic;
                [[EMClient sharedClient].chatManager updateMessage:model.message completion:^(EMMessage *aMessage, EMError *aError) {
                }];
                NSDictionary *ext = @{@"hx_attr_show_wx_account":@(YES),
                                      @"hx_attr_show_other_wx_account":to_weixin,
                                      @"hx_attr_show_my_wx_account":weixin
                                      };
                NSString *m1_name = [model.message.ext m1_stringKey:@"nick_name"];
                if (m1_name.length >6) {
                    m1_name = [NSString stringWithFormat:@"%@...",[m1_name substringWithRange:NSMakeRange(0, 6)]];
                }
                NSString *str = [NSString stringWithFormat:@"%@的微信号：%@",m1_name,to_weixin];
                [weakSelf sendTextMessage:str withExt:ext];
                
            } fail:^(id resDic, NSInteger code, NSString *message) {
                if (code == -10014) {
                    //会员
                    [M1Alert m1_alertWithTitle:nil message:@"只有成为加V会员才能和Ta人交换微信号" buttonTitles:@[@"取消",@"确定"] action:^(NSInteger index) {
                        if (index == 1) {
                            //会员
                        }
                    }];
                }else if (code == -70000){
                    //填写微信
                    [M1Alert m1_alertWithTitle:nil message:message buttonTitles:@[@"取消",@"确定"] action:^(NSInteger index) {
                        if (index == 1) {
                            M1EditInformationTextFieldVC *textfieldVC = [[M1EditInformationTextFieldVC alloc] init];
                            textfieldVC.titleStr = @"微信号";
                            [weakSelf.navigationController pushViewController:textfieldVC animated:YES];
                        }
                    }];
                }else if (code == -40000){
                    [M1Alert m1_alertWithTitle:nil message:message buttonTitles:@[@"取消",@"确定"] action:^(NSInteger index) {
                        if (index == 1) {
                            M1RealNameViewController *m1_idenVC = [[M1RealNameViewController alloc] init];
                            [weakSelf.navigationController pushViewController:m1_idenVC animated:YES];
                        }
                    }];
                }
                else{
                   [M1Alert m1_alertWithTitle:nil message:message];
                }
                
            } showAni:YES];
       }
    }
}

- (UITableViewCell *)messageViewController:(UITableView *)tableView
                       cellForMessageModel:(id<IMessageModel>)messageModel
{
    NSDictionary *ext = messageModel.message.ext;
    if ([ext objectForKey:@"em_recall"]) {
        NSString *TimeCellIdentifier = [EaseMessageTimeCell cellIdentifier];
        EaseMessageTimeCell *recallCell = (EaseMessageTimeCell *)[tableView dequeueReusableCellWithIdentifier:TimeCellIdentifier];
        if (recallCell == nil) {
            recallCell = [[EaseMessageTimeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TimeCellIdentifier];
            recallCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        EMTextMessageBody *body = (EMTextMessageBody*)messageModel.message.body;
        recallCell.title = body.text;
        return recallCell;
    }
    return nil;
}
- (CGFloat)messageViewController:(EaseMessageViewController *)viewController
           heightForMessageModel:(id<IMessageModel>)messageModel
                   withCellWidth:(CGFloat)cellWidth
{
    NSDictionary *ext = messageModel.message.ext;
    if ([ext objectForKey:@"em_recall"]) {
        return self.timeCellHeight;
    }
    return 0;
}
- (BOOL)messageViewController:(EaseMessageViewController *)viewController
   canLongPressRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (BOOL)messageViewController:(EaseMessageViewController *)viewController
   didLongPressRowAtIndexPath:(NSIndexPath *)indexPath
{
    id object = [self.dataArray objectAtIndex:indexPath.row];
    if (![object isKindOfClass:[NSString class]]) {
        EaseMessageCell *cell = (EaseMessageCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[EaseMessageCell class]]) {
            [cell becomeFirstResponder];
            self.menuIndexPath = indexPath;
            [self showMenuViewController:cell.bubbleView andIndexPath:indexPath messageType:cell.model.bodyType];
        }
    }
    return YES;
}
- (void)messageViewController:(EaseMessageViewController *)viewController
  didSelectAvatarMessageModel:(id<IMessageModel>)messageModel
{
    if ([messageModel.message.conversationId isEqualToString:[@"100000" m1_MD5]]||[messageModel.message.conversationId isEqualToString:[@"100001" m1_MD5]]||[messageModel.message.conversationId isEqualToString:[@"100002" m1_MD5]]||[messageModel.message.conversationId isEqualToString:[@"100003" m1_MD5]]) {
        return;
    }
    if (!messageModel.isSender) {
        [self m1_goDetail];
    }
}
#pragma mark - EaseMessageViewControllerDataSource
- (id<IMessageModel>)messageViewController:(EaseMessageViewController *)viewController
                           modelForMessage:(EMMessage *)message
{
    id<IMessageModel> model = nil;
    model = [[EaseMessageModel alloc] initWithMessage:message];
    model.avatarImage = [UIImage imageNamed:@"EaseUIResource.bundle/user"];
    NSLog(@"%@",model.message.ext);
    model.avatarURLPath = [model.message.ext m1_stringKey:@"headphoto"];
    model.nickname = [model.message.ext m1_stringKey:@"nick_name"];
    model.failImageName = @"imageDownloadFail";
    return model;
}
- (NSArray*)emotionFormessageViewController:(EaseMessageViewController *)viewController
{
    NSMutableArray *emotions = [NSMutableArray array];
    for (NSString *name in [EaseEmoji allEmoji]) {
        EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:name emotionThumbnail:name emotionOriginal:name emotionOriginalURL:@"" emotionType:EMEmotionDefault];
        [emotions addObject:emotion];
    }
    EaseEmotion *temp = [emotions objectAtIndex:0];
    EaseEmotionManager *managerDefault = [[EaseEmotionManager alloc] initWithType:EMEmotionDefault emotionRow:3 emotionCol:7 emotions:emotions tagImage:[UIImage imageNamed:temp.emotionId]];
    NSMutableArray *emotionGifs = [NSMutableArray array];
    _emotionDic = [NSMutableDictionary dictionary];
    NSArray *names = @[@"icon_002",@"icon_007",@"icon_010",@"icon_012",@"icon_013",@"icon_018",@"icon_019",@"icon_020",@"icon_021",@"icon_022",@"icon_024",@"icon_027",@"icon_029",@"icon_030",@"icon_035",@"icon_040"];
    int index = 0;
    for (NSString *name in names) {
        index++;
        EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:[NSString stringWithFormat:@"[示例%d]",index] emotionId:[NSString stringWithFormat:@"em%d",(1000 + index)] emotionThumbnail:[NSString stringWithFormat:@"%@_cover",name] emotionOriginal:[NSString stringWithFormat:@"%@",name] emotionOriginalURL:@"" emotionType:EMEmotionGif];
        [emotionGifs addObject:emotion];
        [_emotionDic setObject:emotion forKey:[NSString stringWithFormat:@"em%d",(1000 + index)]];
    }
    EaseEmotionManager *managerGif= [[EaseEmotionManager alloc] initWithType:EMEmotionGif emotionRow:2 emotionCol:4 emotions:emotionGifs tagImage:[UIImage imageNamed:@"icon_002_cover"]];
    return @[managerDefault];
}
- (BOOL)isEmotionMessageFormessageViewController:(EaseMessageViewController *)viewController
                                    messageModel:(id<IMessageModel>)messageModel
{
    BOOL flag = NO;
    if ([messageModel.message.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
        return YES;
    }
    return flag;
}
- (EaseEmotion*)emotionURLFormessageViewController:(EaseMessageViewController *)viewController
                                      messageModel:(id<IMessageModel>)messageModel
{
    NSString *emotionId = [messageModel.message.ext objectForKey:MESSAGE_ATTR_EXPRESSION_ID];
    EaseEmotion *emotion = [_emotionDic objectForKey:emotionId];
    if (emotion == nil) {
        emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:emotionId emotionThumbnail:@"" emotionOriginal:@"" emotionOriginalURL:@"" emotionType:EMEmotionGif];
    }
    return emotion;
}
- (NSDictionary*)emotionExtFormessageViewController:(EaseMessageViewController *)viewController
                                        easeEmotion:(EaseEmotion*)easeEmotion
{
    return @{MESSAGE_ATTR_EXPRESSION_ID:easeEmotion.emotionId,MESSAGE_ATTR_IS_BIG_EXPRESSION:@(YES)};
}
- (void)messageViewControllerMarkAllMessagesAsRead:(EaseMessageViewController *)viewController
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
}
#pragma mark - EaseMob
#pragma mark - EMClientDelegate
- (void)userAccountDidLoginFromOtherDevice
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}
- (void)userAccountDidRemoveFromServer
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}
- (void)userDidForbidByServer
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}
#pragma mark - EMChatManagerDelegate
- (void)messagesDidRecall:(NSArray *)aMessages
{
    for (EMMessage *msg in aMessages) {
        if (![self.conversation.conversationId isEqualToString:msg.conversationId]){
            continue;
        }
        NSString *text;
        if ([msg.from isEqualToString:[EMClient sharedClient].currentUsername]) {
            text = [NSString stringWithFormat:NSLocalizedString(@"message.recall", @"You recall a message")];
        } else {
            text = [NSString stringWithFormat:NSLocalizedString(@"message.recallByOthers", @"%@ recall a message"),msg.from];
        }
        [self _recallWithMessage:msg text:text isSave:NO];
    }
}
#pragma mark - action

- (void)recallMenuAction:(id)sender
{
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        __weak typeof(self) m1_weakSelf = self;
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        [[EMClient sharedClient].chatManager recallMessage:model.message
                                                completion:^(EMMessage *aMessage, EMError *aError) {
                                                    if (!aError) {
                                                        [m1_weakSelf _recallWithMessage:aMessage text:NSLocalizedString(@"message.recall", @"You recall a message") isSave:YES];
                                                    } else {
                                                        [m1_weakSelf showHint:[NSString stringWithFormat:NSLocalizedString(@"recallFailed", @"Recall failed:%@"), aError.errorDescription]];
                                                    }
                                                    m1_weakSelf.menuIndexPath = nil;
                                                }];
    }
}
- (void)copyMenuAction:(id)sender
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        pasteboard.string = model.text;
    }
    self.menuIndexPath = nil;
}
- (void)deleteMenuAction:(id)sender
{
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        NSMutableIndexSet *indexs = [NSMutableIndexSet indexSetWithIndex:self.menuIndexPath.row];
        NSMutableArray *indexPaths = [NSMutableArray arrayWithObjects:self.menuIndexPath, nil];
        [self.conversation deleteMessageWithId:model.message.messageId error:nil];
        [self.messsagesSource removeObject:model.message];
        if (self.menuIndexPath.row - 1 >= 0) {
            id nextMessage = nil;
            id prevMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row - 1)];
            if (self.menuIndexPath.row + 1 < [self.dataArray count]) {
                nextMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row + 1)];
            }
            if ((!nextMessage || [nextMessage isKindOfClass:[NSString class]]) && [prevMessage isKindOfClass:[NSString class]]) {
                [indexs addIndex:self.menuIndexPath.row - 1];
                [indexPaths addObject:[NSIndexPath indexPathForRow:(self.menuIndexPath.row - 1) inSection:0]];
            }
        }
        [self.dataArray removeObjectsAtIndexes:indexs];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        if ([self.dataArray count] == 0) {
            self.messageTimeIntervalTag = -1;
        }
    }
    self.menuIndexPath = nil;
}
#pragma mark - notification
- (void)exitChat
{
    [self.navigationController popToViewController:self animated:NO];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)insertCallMessage:(NSNotification *)notification
{
    id object = notification.object;
    if (object) {
        EMMessage *message = (EMMessage *)object;
        [self addMessageToDataSource:message progress:nil];
        [[EMClient sharedClient].chatManager importMessages:@[message] completion:nil];
    }
}
- (void)handleCallNotification:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        self.isViewDidAppear = NO;
    } else {
        self.isViewDidAppear = YES;
    }
}
#pragma mark - private
- (void)showMenuViewController:(UIView *)showInView
                  andIndexPath:(NSIndexPath *)indexPath
                   messageType:(EMMessageBodyType)messageType
{
    if (self.menuController == nil) {
        self.menuController = [UIMenuController sharedMenuController];
    }
    if (m1__deleteItem == nil) {
        m1__deleteItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"delete", @"Delete") action:@selector(deleteMenuAction:)];
    }
    if (m1_copyItem == nil) {
        m1_copyItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"copy", @"Copy") action:@selector(copyMenuAction:)];
    }
    if (m1_transpondItem == nil) {
        m1_transpondItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"transpond", @"Transpond") action:@selector(transpondMenuAction:)];
    }
    if (m1_recallItem == nil) {
        m1_recallItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"recall", @"Recall") action:@selector(deleteMenuAction:)];
    }
    NSMutableArray *items = [NSMutableArray array];
    if (messageType == EMMessageBodyTypeText) {
        [items addObject:m1_copyItem];
        [items addObject:m1_transpondItem];
        [items addObject:m1__deleteItem];
    } else if (messageType == EMMessageBodyTypeImage || messageType == EMMessageBodyTypeVideo) {
        [items addObject:m1_transpondItem];
        [items addObject:m1__deleteItem];
    } else {
        [items addObject:m1__deleteItem];
    }
    id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
    if (model.isSender) {
        [items addObject:m1_recallItem];
    }
    [self.menuController setMenuItems:items];
    [self.menuController setTargetRect:showInView.frame inView:showInView.superview];
    [self.menuController setMenuVisible:YES animated:YES];
}
- (void)_recallWithMessage:(EMMessage *)msg text:(NSString *)text isSave:(BOOL)isSave
{
    EMMessage *message = [EaseSDKHelper getTextMessage:text to:msg.conversationId messageType:msg.chatType messageExt:@{@"em_recall":@(YES)}];
    message.isRead = YES;
    [message setTimestamp:msg.timestamp];
    [message setLocalTime:msg.localTime];
    id<IMessageModel> newModel = [[EaseMessageModel alloc] initWithMessage:message];
    __block NSUInteger index = NSNotFound;
    [self.dataArray enumerateObjectsUsingBlock:^(EaseMessageModel *model, NSUInteger idx, BOOL *stop){
        if ([model conformsToProtocol:@protocol(IMessageModel)]) {
            if ([msg.messageId isEqualToString:model.message.messageId])
            {
                index = idx;
                *stop = YES;
            }
        }
    }];
    if (index != NSNotFound)
    {
        __block NSUInteger sourceIndex = NSNotFound;
        [self.messsagesSource enumerateObjectsUsingBlock:^(EMMessage *message, NSUInteger idx, BOOL *stop){
            if ([message isKindOfClass:[EMMessage class]]) {
                if ([msg.messageId isEqualToString:message.messageId])
                {
                    sourceIndex = idx;
                    *stop = YES;
                }
            }
        }];
        if (sourceIndex != NSNotFound) {
            [self.messsagesSource replaceObjectAtIndex:sourceIndex withObject:newModel.message];
        }
        [self.dataArray replaceObjectAtIndex:index withObject:newModel];
        [self.tableView reloadData];
    }
    if (isSave) {
        [self.conversation insertMessage:message error:nil];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
